<?php

/**
 * Url 工具类
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-01
 */

namespace fw\tool;

use fw\base\Conf;

class Url
{
    /**
     * 返回网站根目录
     *
     * @return string
     */
    public static function root()
    {
        $len = strrpos($_SERVER['PHP_SELF'], '/');
        $path = substr($_SERVER['PHP_SELF'], 0, $len + 1);

        return $path;
    }

    /**
     * url 生成器
     *
     * @param string $path
     * @param array  $map
     * @param string $script
     *
     * @return string
     */
    public static function to($path = '', $map = [], $script = '')
    {
        $base_url = !empty($script) ? self::root() . $script : $_SERVER['PHP_SELF'];
        $path = Str::humpToLine($path);
        $query = http_build_query($map);

        $p = explode('/', $path);
        $c = !empty($p[0]) ? "c={$p[0]}&" : "";
        $m = !empty($p[1]) ? "m={$p[1]}&" : "";

        if (!empty($c) || !empty($m) || !empty($query)) {
            $query = '?' . $c . $m . $query;
            $query = rtrim($query, '&');
        }

        $url = $base_url . $query;

        return self::reWrite($url);
    }

    /**
     * url 重写
     *
     * @param string $url
     *
     * @return string
     */
    public static function reWrite($url)
    {
        if (isset(Conf::$all['is_rewrite']) && Conf::$all['is_rewrite'] === true) {

            $rules = [
                '/index\.php\?c=page&m=show&alias=(\w+)/'          => '$1.html',
                '/index\.php\?c=(\w+)&m=show&id=(\d)/'             => '$1/$2',

                // 下面是常见的重写规则

                '/index\.php\?c=(\w+)&m=(\w+)$/'     => '$1/$2',
                '/index\.php\?c=(\w+)$/'             => '$1',
            ];

            $pattern = array_keys($rules);
            $replacement = array_values($rules);

            $url = preg_replace($pattern, $replacement, $url);
        }

        return $url;
    }
}
